package com.cavy.platform.server.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public final class HttpServletResponseHelper {
    private HttpServletResponseHelper() {
    }

    /**
     * 输出文件到http响应中
     *
     * @param target   目标文件
     * @param response 响应实例
     */
    public static void writeFile(File target, HttpServletResponse response) {
        byte[] buffer = new byte[1024 * 5];
        int bytesRead;
        try (FileInputStream fis = new FileInputStream(target); ServletOutputStream outputStream = response.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
